package com.mxsoft.takeaway.component;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.gson.Gson;
import com.mxsoft.takeaway.model.Customer;
import com.mxsoft.takeaway.model.ElemeMessage;
import com.mxsoft.takeaway.model.MessageRecord;
import com.mxsoft.takeaway.model.MessageTemplate;
import com.mxsoft.takeaway.service.ICustomerService;
import com.mxsoft.takeaway.service.IElemeMessageService;
import com.mxsoft.takeaway.service.IMessageRecordService;
import com.mxsoft.takeaway.service.IMessageTemplateService;
import com.mxsoft.takeaway.util.eleme.ElemeMessageTypeConstant;
import com.mxsoft.takeaway.util.eleme.ElemeUtil;
import eleme.openapi.sdk.api.entity.order.CompensationOrder;
import eleme.openapi.sdk.api.entity.order.OOrder;
import eleme.openapi.sdk.api.entity.other.OMessage;
import eleme.openapi.ws.sdk.Bootstrap;
import eleme.openapi.ws.sdk.config.Config;
import eleme.openapi.ws.sdk.config.ElemeSdkLogger;
import eleme.openapi.ws.sdk.entity.Account;
import eleme.openapi.ws.sdk.exception.UnableConnectionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @author zhangyingxuan
 */
@Slf4j
@Component
public class ElemeBootstrapComponent {

    @Autowired
    private IElemeMessageService elemeMessageService;

    @Autowired
    private IMessageRecordService messageRecordService;

    @Autowired
    private IMessageTemplateService messageTemplateService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    private Gson gson = new Gson();

    @PostConstruct
    public void init() {
        eleme.openapi.sdk.config.Config config1 = ElemeUtil.getConfig();
        Account account = new Account(config1.getApp_key(), config1.getApp_secret());
        List<Account> accounts = new ArrayList<>();
        accounts.add(account);
        Config config = new Config(accounts,
                message -> {
                    //你的业务消息处理,推荐直接落地存储,不要耦合过重业务
                    log.info(message);

                    threadPoolTaskExecutor.submit(() -> {
                        OMessage map = gson.fromJson(message, OMessage.class);
                        ElemeMessage elemeMessage = new ElemeMessage();
                        elemeMessage.setContent(message);
                        elemeMessage.setCreateBy("system");
                        elemeMessage.setRequestId(map.getRequestId());
                        elemeMessage.setType(map.getType());

                        elemeMessage.setMemo(map.getMessage());

                        if (ElemeMessageTypeConstant.order_valid_success == map.getType()) {
                            OOrder oOrder = gson.fromJson(map.getMessage(), OOrder.class);
                            elemeMessage.setOrderId(oOrder.getId());

                            generateCustomer(oOrder);
                        } else if (ElemeMessageTypeConstant.order_send_success == map.getType()) {
                            CompensationOrder compensationOrder = gson.fromJson(map.getMessage(), CompensationOrder.class);
                            elemeMessage.setOrderId(compensationOrder.getOrderId());

                            generateMessageRecord(compensationOrder.getOrderId());
                        }

                        log.info("begin store message requestId: {}", map.getRequestId());
                        elemeMessageService.insert(elemeMessage);
                        log.info("end store message requestId: {}", map.getRequestId());

                    });

                    return true;
                },
                new ElemeSdkLogger() {
                    @Override
                    public void info(String message) {
                        //your info log 处理
                        log.info(message);
                    }

                    @Override
                    public void error(String message) {
                        //your error log 处理
                        log.error(message);
                    }
                }
        );
        try {
            Bootstrap.start(config);
        } catch (UnableConnectionException e) {
            e.printStackTrace();
        }
    }

    private void generateCustomer(OOrder oOrder) {
        List<String> phoneList = oOrder.getPhoneList();

        if (CollectionUtils.isEmpty(phoneList)) {
            return;
        }

        String deliveryPoiAddress = oOrder.getDeliveryPoiAddress();
        int userId = oOrder.getUserId();
        String customerName = oOrder.getConsignee();

        List<Customer> customers = new ArrayList<>(phoneList.size());
        for (String phone : phoneList) {

            List<Customer> customerList = customerService.selectList(new EntityWrapper<Customer>().eq("id_delete", 0).eq("phone", phone));
            if (!CollectionUtils.isEmpty(customerList)) {
                continue;
            }

            Customer customer = new Customer();
            customer.setAddress(deliveryPoiAddress);
            customer.setPhone(phone);
            customer.setUserId(Long.valueOf(userId));
            customer.setCustomerName(customerName);

            customers.add(customer);
        }

        customerService.insertBatch(customers);

        log.info("add customers : {}", customers);
    }

    private void generateMessageRecord(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return;
        }

        ElemeMessage elemeMessage = elemeMessageService.selectOne(new EntityWrapper<ElemeMessage>().eq("orderId", orderId).eq("type", ElemeMessageTypeConstant.order_valid_success));
        if (null == elemeMessage) {
            log.error("订单：{} 没有对应的详细信息 ", orderId);
            return;
        }

        MessageTemplate messageTemplate = messageTemplateService.selectOne(new EntityWrapper<MessageTemplate>().eq("type", ElemeMessageTypeConstant.order_send_success));

        if (null == messageTemplate) {
            log.error("没有配置消息模板");
            return;
        }

        OOrder oOrder = gson.fromJson(elemeMessage.getMemo(), OOrder.class);
        List<String> phoneList = oOrder.getPhoneList();

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR_OF_DAY, 1);

        List<MessageRecord> data = new ArrayList<>(phoneList.size());
        for (String phone : phoneList) {
            MessageRecord messageRecord = new MessageRecord();
            messageRecord.setTarget(phone);
            messageRecord.setSendTime(instance.getTime());
            messageRecord.setContent(messageTemplate.getContent());
            data.add(messageRecord);
        }

        messageRecordService.insertBatch(data);
    }

}
